from rest_framework import serializers
from question.models import Question, Answer, Label
from users.models import User


class LabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ('name',)


class QuestionListSerializer(serializers.ModelSerializer):
    """问题列表序列化器"""
    author = serializers.StringRelatedField(label='作者')
    labels = LabelSerializer(many=True)

    # labels = serializers.SlugRelatedField(slug_field="name",read_only=True)

    class Meta:
        model = Question
        exclude = ('update_time', 'content')


class QuestionDetailSerializer(serializers.ModelSerializer):
    """问题详情序列化器"""
    author = serializers.StringRelatedField(label='作者')
    labels = LabelSerializer(many=True)

    class Meta:
        model = Question
        exclude = ('update_time',)


class QuestionCreateSerializer(serializers.ModelSerializer):
    """提交问题序列化器"""
    labels = LabelSerializer(many=True)

    class Meta:
        model = Question
        exclude = ('update_time', 'create_time', 'like_count', 'answer_count', 'click_count')

    def create(self, validated_data):
        labels_data = validated_data.pop('labels', [])
        question = Question.objects.create(**validated_data)
        for label in labels_data:
            label_name = label.get('name')
            label_object = Label.objects.get(name=label_name)
            question.labels.add(label_object)
        return question

    def validate_author(self, value):
        print(value)
        # try:
        #     User.objects.filter(username=value)
        # except User.DoesNotExist:
        #     raise serializers.ValidationError("用户身份错误")
        return value

    def validate_labels(self, value):
        for label_dict in value:
            try:
                Label.objects.get(name=label_dict.get('name'))
            except Label.DoesNotExist:
                raise serializers.ValidationError('标签类型错误')
        return value


class QuestionUpdateSerializer(serializers.ModelSerializer):
    """问题点赞序列化器"""
    class Meta:
        model = Question
        fields = ('like_count',)


class AnswerSerializer(serializers.ModelSerializer):
    """答案详情序列化器"""
    class Meta:
        model = Answer
        fields = ('id', 'content', 'question', 'like_count')


class AnswerUpdateSerializer(serializers.ModelSerializer):
    """答案点赞序列化器"""
    class Meta:
        model = Answer
        fields = ('like_count',)
